﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace CraigsCrawler
{
    public static class Utilities
    {
        public static string GetCity(string link)
        {
            if (String.IsNullOrWhiteSpace(link)) return null;

            Regex regex = new Regex(@"^http:\/\/([a-zA-Z0-9-_]+)\..*$");
            Match match = regex.Match(link);
            if (!match.Success) return null;

            return match.Groups[1].Value;
        }

        public static void SuppressDuplicates(Entry entryToSuppress)
        {
            SearchStorage storage = entryToSuppress.parent;

            if (!storage.suppressedTitles.Any(t => t.Item1 == entryToSuppress.title && t.Item2 == entryToSuppress.city))
            {
                storage.suppressedTitles.Add(Tuple.Create(entryToSuppress.title, entryToSuppress.city));
            }

            IEnumerable<Entry> entries = storage.entries.Where(e => e.title == entryToSuppress.title).OrderByDescending(e => e.posted);

            bool foundFirst = false;

            foreach (Entry entry in entries)
            {
                if (entry.entryState == EntryState.ManuallyIgnored || foundFirst)
                {
                    entry.entryState = EntryState.AutomaticallyIgnored;
                    Querier.Current.TailQueueByContext(entry);
                }
                else if (entry.entryState == EntryState.Interested || entry.entryState == EntryState.New)
                {
                    foundFirst = true;
                }
            }

            storage.Save();
        }

        public static void ForEach<T>(this IEnumerable<T> items, Action<T> action)
        {
            foreach (T item in items)
            {
                action(item);
            }
        }
    }
}
